package users

import (
	"fmt"
	"go-demo-2025/common"
	"go-demo-2025/models/model"
	"go-demo-2025/service"
	"go-demo-2025/utils/funcUtils"
	"strconv"
)

type UserService struct {
	*service.BaseService
}

func NewUserService() *UserService {
	return &UserService{
		service.NewBaseService(),
	}
}

// 获取用户列表, 客户端的请求参数
type UserListRequest struct {
	Name  string `json:"name"  binding:"required"` //用户姓名关键词,假设此处要求检索的时候必填
	Email string `json:"email"`                    //用户邮箱
	common.CommonListRequest
}

// 获取用户列表, 服务端的响应结构体, 在原有的数据表结构的基础上进行扩展
type UserListResponse struct {
	model.User
	NamePinyin string `json:"name_pinyin"`
	AgeDesc    string `json:"age_desc"`
	StatusDesc string `json:"status_desc"`
}

// 批量添加mock数据
func (ctx *UserService) BatchCreateMockData() {
	for i := 1; i <= 50; i++ { //循环操作82次
		var users []*model.User
		for j := 1; j <= 100; j++ { //一次添加100条数据
			userid := "1" + fmt.Sprintf("%03d", i) + fmt.Sprintf("%03d", j)
			useridInt, _ := strconv.Atoi(userid)
			name := funcUtils.GenerateRandomChineseName()
			users = append(users, &model.User{
				UserID:  int64(useridInt),
				UUID:    common.CreateUuid(),
				Name:    name,
				Age:     int64(common.GenerateRandomNumber()),
				Email:   fmt.Sprintf("%v@test.com", common.ConvertChineseToPinyin(name)),
				Address: funcUtils.GenerateRandomChinaAddress(),
				Status:  2,
				Extra:   "{}",
			})
		}
		err := ctx.GormDB.Create(users).Error
		if err != nil {
			fmt.Println(fmt.Sprintf("第 %d 页添加失败,错误原因:%s", i, err))
		} else {
			fmt.Println(fmt.Sprintf("第 %d 页添加成功", i))
		}
	}
}

// gorm 查询方法文档: https://gorm.io/zh_CN/docs/query.html

// 查询总数
func (ctx *UserService) GetUserCount() int64 {
	var count int64
	err := ctx.GormDB.Model(&model.User{}).Where("1=1").Count(&count).Error
	if err != nil {
		fmt.Println(fmt.Sprintf("查询总数错误:%s", err))
		return 0
	}
	//fmt.Println(fmt.Sprintf("总条数:%d", count))
	return count
}

func (ctx *UserService) GetUserList(page int, pageSize int) []model.User {
	var dataList []model.User
	offset := (page - 1) * pageSize //偏移量
	err2 := ctx.GormDB.Select("*").Where("1=1").Order("id asc").Limit(pageSize).Offset(offset).Find(&dataList).Error
	if err2 != nil {
		fmt.Println(fmt.Sprintf("查询列表错误:%s", err2))
		return nil
	}
	return dataList
}

// 同时查询列表和总数 https://www.cnblogs.com/rainbow-tan/p/15822714.html
func (ctx *UserService) QueryUserList(params UserListRequest) ([]UserListResponse, int64) {
	//gorm 查询方法文档: https://gorm.io/zh_CN/docs/query.html
	//查询条件
	//fmt.Println(params)
	where := "1=1"
	if params.Name != "" {
		where += " and name like '%" + params.Name + "%'"
	}
	if params.Email != "" {
		where += " and email = '" + params.Email + "'"
	}

	//查询总数和列表
	var dataList []UserListResponse
	var count int64
	page := params.Page             //当前第几页
	pageSize := params.PageSize     //每页查询多少条
	offset := (page - 1) * pageSize //偏移量
	err := ctx.GormDB.Model(&model.User{}).
		Select("*").
		Where(where).
		Order("id desc").
		Limit(pageSize).
		Offset(offset).
		Scan(&dataList).
		Limit(-1).
		Offset(-1).
		Count(&count).Error
	if err != nil {
		fmt.Println(fmt.Sprintf("数据库查询错误:%s", err))
		return nil, 0
	}

	fmt.Println(fmt.Sprintf("总条数:%d", count))
	statusMap := map[int64]string{ //状态:1审核中,2正常,3禁用,4封号
		1: "审核中",
		2: "正常",
		3: "禁用",
		4: "封号",
	}
	for k, v := range dataList {
		var ageDesc string
		if v.Age >= 18 {
			ageDesc = "成年"
		} else {
			ageDesc = "未成年"
		}
		dataList[k].AgeDesc = ageDesc
		dataList[k].NamePinyin = common.ConvertChineseToPinyin(v.Name)
		dataList[k].StatusDesc = statusMap[v.Status]
	}
	return dataList, count
}

func (ctx *UserService) QueryUserDetail(id int64) UserListResponse {
	var dataDetail UserListResponse
	rs := ctx.GormDB.Where("id = ?", id).First(&dataDetail)
	if rs.Error != nil {
		fmt.Println(fmt.Sprintf("数据库查询错误:%s", rs.Error))
		return UserListResponse{}
	}

	return dataDetail
}

func (ctx *UserService) AddCustomer(data model.User) (bool, error) {
	data.UUID = common.CreateUuid()
	data.Address = funcUtils.GenerateRandomChinaAddress()
	fmt.Println("userService.AddCustomer.data:", data)

	// 执行添加数据
	res := ctx.GormDB.Create(&data)
	fmt.Println("res.Error:", res.Error)
	if res.Error != nil {
		return false, res.Error
	}

	return true, nil
}
